import {NotifyPopup} from '@kintone/kintone-ui-component/esm/js';
import util from './util';

export class ErrorHandler {
  constructor() {
    const bodyNode = document.getElementsByTagName('body');
    if (bodyNode.length === 0) {
      throw new Error('No body element, fail to create NotifyPopup !');
    } else {
      this.notify = new NotifyPopup({isVisible: false});
      bodyNode[0].appendChild(this.notify.render());
    }
  }

  throwError(error, prefix = '') {
    if (error instanceof Error) {
      if (this.notify) {
        this.notify.setText(error.message);
        this.notify.show();
      }
      throw error;
    } else {
      let errorMessage = util.isEmptyString(prefix) ? '' : `[${prefix}] `;
      if (typeof error === 'string') {
        errorMessage += util.isEmptyString(error) ? '未知错误' : `错误: ${error}`;
      } else if (typeof error === 'object') {
        if (typeof error.status === 'number') {
          errorMessage += `[${error.status}] `;
        } else {
          errorMessage += (util.isEmptyString(error.status) ? '' : `[${error.status}] `);
        }
        errorMessage += (util.isEmptyString(error.message) ? '未知错误' : `错误: ${error.message}`);
      } else {
        errorMessage += '未知错误';
      }
      if (this.notify) {
        this.notify.setText(errorMessage);
        this.notify.show();
      }
      throw new Error(errorMessage);
    }
  }
}